import {removeToken, setToken} from "@/utils/auth";
import {getUserInfo, login} from "@/api/user";
import {resetRouter} from '@/router'

const state = {
    user: {
        username: '',
        password: '',
        hasRoute: false
    },
}
const getters = {
    user(state) {
        return state.user;
    }
}
const mutations = {
    SET_USER(state, payload) {
        state.user = payload
        let token = payload.token
        setToken(token)
    },
    LOGOUT(state) {
        state.user = {}
        removeToken()
        resetRouter()
    }
}
// const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms))

const actions = {
    async login({commit}, payload,) {
        return login(payload).then(res => {
            let success = res.success;
            commit('SET_USER', payload)
            if (success && res.data) {
                commit('SET_USER', res.data)
            }
            return res
        }).catch(err => {
            console.log(err)
            return err
        })
    },
    logout({commit}) {
        commit('LOGOUT')
    },
    async getUserInfo({commit}) {
        return getUserInfo({username: state.user.username}).then(res => {
            const data = res
            commit('SET_USER', {username: data.username, password: data.password, hasRoute: true})
            return data
        })
    },
}
export default {
    namespaced: true,
    state,
    getters,
    mutations,
    actions
}
